<template>
  <div class="footer-tools">
    <!-- 左侧控制按钮 -->
    <div class="tools-left">
      <!-- 记忆按钮 -->
      <n-popover trigger="hover" placement="top" :show-arrow="true" :overlap="false" class="custom-popover">
        <template #trigger>
          <n-icon class="footer-tool-icon" :class="{ 'memory-enabled': config.enableMemory }" @click="toggleMemory">
            <SaveOutline />
          </n-icon>
        </template>
        <span class="popover-text">记忆</span>
      </n-popover>

      <!-- 提示词模板选择器 -->
      <n-popover
        trigger="hover"
        placement="top"
        :show-arrow="true"
        :overlap="false"
        class="prompt-popover"
      >
        <template #trigger>
          <n-icon
            class="footer-tool-icon"
            :class="{ 'prompt-enabled': selectedTemplate && promptActive, 'prompt-active': promptActive }"
            @click="onPromptIconClick"
          >
            <SparklesOutline />
          </n-icon>
        </template>
        <div class="prompt-template-selector">
          <div class="prompt-header">
            <span class="prompt-title">提示词模板</span>
            <n-button v-if="selectedTemplate" size="tiny" type="default" @click.stop="clearTemplate">
              清除
            </n-button>
          </div>
          <div class="template-list">
            <n-scrollbar style="max-height: 300px;">
              <div v-for="template in promptTemplates" :key="template.id"
                   class="template-item" :class="{selected: selectedTemplate && selectedTemplate.id === template.id}" @click="toggleTemplate(template)">
                <div class="template-item-name">{{ template.name }}</div>
                <div v-if="selectedTemplate && selectedTemplate.id === template.id" class="knowledge-item-check">
                  <n-icon size="16" color="#16baaa">
                    <CheckmarkOutline />
                  </n-icon>
                </div>
              </div>
            </n-scrollbar>
          </div>
        </div>
      </n-popover>

      <!-- 知识库按钮 -->
      <n-popover
        trigger="hover"
        placement="top"
        :show-arrow="true"
        :overlap="false"
        class="knowledge-popover"
      >
        <template #trigger>
          <n-icon
            class="footer-tool-icon"
            :class="{ 'knowledge-enabled': selectedKnowledgeBase && knowledgeActive, 'knowledge-active': knowledgeActive }"
            @click="onKnowledgeIconClick"
          >
            <ServerOutline/>
          </n-icon>
        </template>
        <div class="knowledge-base-selector">
          <div class="knowledge-header">
            <span class="knowledge-title">知识库</span>
            <n-button v-if="selectedKnowledgeBase" size="tiny" type="default" @click.stop="clearKnowledgeBase">
              清除
            </n-button>
          </div>

          <div class="knowledge-list">
            <n-scrollbar style="max-height: 300px;">
              <div v-for="kb in knowledgeBases" :key="kb.kbId"
                   class="knowledge-item" :class="{selected: selectedKnowledgeBase && selectedKnowledgeBase.kbId === kb.kbId}" @click="toggleKnowledgeBase(kb)">
                <div class="knowledge-item-name">{{ kb.name }}</div>
                <div v-if="selectedKnowledgeBase && selectedKnowledgeBase.kbId === kb.kbId" class="knowledge-item-check">
                  <n-icon size="16" color="#16baaa">
                    <CheckmarkOutline />
                  </n-icon>
                </div>
              </div>
            </n-scrollbar>
          </div>
        </div>
      </n-popover>

      <!-- 工具按钮 -->
      <n-popover trigger="hover" placement="top" :show-arrow="true" :overlap="false" class="custom-popover">
        <template #trigger>
          <n-icon class="footer-tool-icon" :class="{ 'tools-enabled': config.enableTools }" @click="toggleTools">
            <ConstructOutline />
          </n-icon>
        </template>
        <span class="popover-text">AI工具</span>
      </n-popover>

      <!-- 图片按钮 -->
      <n-popover trigger="hover" placement="top" :show-arrow="true" :overlap="false" class="custom-popover">
        <template #trigger>
          <n-icon class="footer-tool-icon" :class="{ 'image-enabled': hasImages }" @click="$emit('image-upload')">
            <ImageOutline />
          </n-icon>
        </template>
        <span class="popover-text">图片上传</span>
      </n-popover>
      
      <!-- 文档上传按钮 -->
      <n-popover trigger="hover" placement="top" :show-arrow="true" :overlap="false" class="custom-popover">
        <template #trigger>
          <n-icon class="footer-tool-icon" :class="{ 'document-enabled': hasDocuments }" @click="handleDocumentUpload">
            <Attach />
          </n-icon>
        </template>
        <span class="popover-text">文档上传</span>
      </n-popover>
      
      <!-- 模型切换器 -->
      <ModelSelector ref="modelSelectorRef" :current-model="modelStore.currentChatModel || config.currentModelId || config.defaultModel" @select-model="selectModel" />
      
      <!-- 清空消息按钮 -->
      <n-popover trigger="hover" placement="top" :show-arrow="true" :overlap="false" class="custom-popover">
        <template #trigger>
          <n-icon class="footer-tool-icon" @click="$emit('clear-messages')">
            <TrashOutline />
          </n-icon>
        </template>
        <span class="popover-text">清空消息</span>
      </n-popover>
    </div>

    <!-- 右侧操作按钮 -->
    <div class="tools-right">
      <!-- 新会话按钮 -->
      <n-popover trigger="hover" placement="top" :show-arrow="true" :overlap="false" class="custom-popover">
        <template #trigger>
          <n-icon class="footer-tool-icon" @click="createNewSession">
            <AddCircleOutline />
          </n-icon>
        </template>
        <span class="popover-text">新建会话</span>
      </n-popover>

      <!-- 历史会话按钮 -->
      <n-popover trigger="hover" placement="top" :show-arrow="true" :overlap="false" class="custom-popover">
        <template #trigger>
          <n-icon class="footer-tool-icon" @click="openHistoryDrawer">
            <TimeOutline />
          </n-icon>
        </template>
        <span class="popover-text">历史会话</span>
      </n-popover>

      <!-- 导出聊天记录按钮 -->
      <n-popover trigger="hover" placement="top" :show-arrow="true" :overlap="false" class="custom-popover">
        <template #trigger>
          <n-icon class="footer-tool-icon" @click="exportChat">
            <CloudDownloadOutline />
          </n-icon>
        </template>
        <span class="popover-text">导出聊天记录</span>
      </n-popover>
    </div>
  </div>

  <!-- 历史会话抽屉 -->
  <HistoryDrawer
    ref="historyDrawerRef"
    :show="showDrawer"
    :current-session-id="currentSessionId"
    :user-id="numericUserId"
    @update:show="showDrawer = $event"
    @session-selected="selectSession"
  />
  
  <!-- 隐藏的ChatExport组件用于导出功能 -->
  <ChatExport
    ref="chatExportRef"
    :messages="chatMessages"
    :session-id="currentSessionId"
    :session-title="currentSessionTitle"
    @export-start="onExportStart"
    @export-success="onExportSuccess"
    @export-error="onExportError"
    style="display: none;"
  />
</template>

<script setup lang="ts">
import { NIcon, NPopover, NButton, NScrollbar, useMessage } from 'naive-ui'
import { AddCircleOutline, ConstructOutline, TrashOutline, ImageOutline,SparklesOutline,ServerOutline,CheckmarkOutline,TimeOutline,SaveOutline,Attach,CloudDownloadOutline } from '@vicons/ionicons5'
import { ref, computed, onMounted } from 'vue'
import ModelSelector from './ModelSelector.vue'
import HistoryDrawer from './HistoryDrawer.vue'
import ChatExport from './ChatExport.vue'
import { useRouter } from 'vue-router'
import { useModelStore } from '../../shared/stores/model'
import { useUserStore } from '../../auth/stores/user'
import { useChatStore } from '../stores/chat'
import { usePromptStore } from '../../shared/stores/prompt'
import type { ChatConfig } from '../../../types/chat'

const props = defineProps<{
  config: ChatConfig
  currentSessionId: string
  userId: number | string  // 修改为接受number或string类型
  chatMessages: any[]
  currentSessionTitle: string
}>()

const emit = defineEmits<{
  'update:config': [config: ChatConfig]
  'clear-messages': []
  'image-upload': []
  'document-upload': [documents: string[], documentNames: string[]]
  'update-session-title': [sessionId: string, title: string]
  'template-selected': [templateId: number | null]
}>()

const router = useRouter()
const message = useMessage()
const modelStore = useModelStore()
const userStore = useUserStore()
const chatStore = useChatStore()
const promptStore = usePromptStore()

// 确保userId是数字类型
const numericUserId = computed(() => {
  return typeof props.userId === 'string' ? parseInt(props.userId, 10) || 0 : props.userId
})

// 状态管理
const showDrawer = ref(false)
const knowledgeActive = ref(false)
const selectedKnowledgeBase = ref<any>(null)
const modelSelectorRef = ref()
const chatExportRef = ref()
const historyDrawerRef = ref()

// 使用ChatStore中的提示词模板状态
const promptActive = computed(() => chatStore.isPromptActive)
const selectedTemplate = computed(() => {
  const templateId = promptStore.getSelectedTemplateId()
  if (!templateId) return null
  return chatStore.promptTemplates.find(template => template.id === templateId) || null
})
const promptTemplates = computed(() => chatStore.promptTemplates)

// 知识库数据
const knowledgeBases = ref<any[]>([])

// 计算属性
const hasImages = computed(() => {
  // 检查是否有图片上传的逻辑
  return false
})

const hasDocuments = computed(() => {
  // 检查是否有文档上传的逻辑
  return false
})

// 方法
const toggleMemory = () => {
  const newConfig = { ...props.config, enableMemory: !props.config.enableMemory }
  emit('update:config', newConfig)
}

const toggleTools = () => {
  const newConfig = { ...props.config, enableTools: !props.config.enableTools }
  emit('update:config', newConfig)
}

const selectModel = (modelId: string | number) => {
  // 确保modelId是number类型，与后端保持一致
  const modelIdNum = Number(modelId)
  
  // 更新modelStore中的currentChatModel
  modelStore.setCurrentChatModel(modelIdNum)
  
  // 更新modelStore中的currentModelId
  modelStore.setCurrentModelId(modelIdNum)
  
  // 同时更新config中的currentModelId
  const newConfig = { ...props.config, currentModelId: modelIdNum }
  emit('update:config', newConfig)
  
  // 关闭模型选择下拉框
  if (modelSelectorRef.value && modelSelectorRef.value.closeDropdown) {
    modelSelectorRef.value.closeDropdown()
  }
}

const onPromptIconClick = () => {
  const newActiveState = !chatStore.isPromptActive
  chatStore.setIsPromptActive(newActiveState)
  if (newActiveState) {
    loadPromptTemplates()
  }
}

const onKnowledgeIconClick = () => {
  knowledgeActive.value = !knowledgeActive.value
  if (knowledgeActive.value) {
    loadKnowledgeBases()
  }
}

const toggleTemplate = (template: any) => {
  if (promptStore.getSelectedTemplateId() && promptStore.getSelectedTemplateId() === template.id) {
    promptStore.saveSelectedTemplateId(null)
    emit('template-selected', null)
  } else {
    promptStore.saveSelectedTemplateId(template.id)
    emit('template-selected', template.id)
  }
}

const clearTemplate = () => {
  promptStore.saveSelectedTemplateId(null)
  emit('template-selected', null)
}

const toggleKnowledgeBase = (kb: any) => {
  if (selectedKnowledgeBase.value && selectedKnowledgeBase.value.kbId === kb.kbId) {
    selectedKnowledgeBase.value = null
  } else {
    selectedKnowledgeBase.value = kb
  }
}

const clearKnowledgeBase = () => {
  selectedKnowledgeBase.value = null
}

const handleDocumentUpload = () => {
  // 文档上传逻辑
  const input = document.createElement('input')
  input.type = 'file'
  input.multiple = true
  input.accept = '.txt,.pdf,.doc,.docx,.md'
  
  input.onchange = (e: any) => {
    const files = Array.from(e.target.files)
    const documents: string[] = []
    const documentNames: string[] = []
    
    files.forEach((file: any) => {
      const reader = new FileReader()
      reader.onload = (event) => {
        documents.push(event.target?.result as string)
        documentNames.push(file.name)
        
        if (documents.length === files.length) {
          emit('document-upload', documents, documentNames)
        }
      }
      reader.readAsText(file)
    })
  }
  
  input.click()
}

const openHistoryDrawer = () => {
  showDrawer.value = true
  // 打开抽屉时，确保当前会话ID已设置
  if (props.currentSessionId) {
    userStore.setCurrentSessionId(props.currentSessionId)
  }
}

const selectSession = (sessionId: string) => {
  // 更新Pinia中的当前会话ID
  userStore.setCurrentSessionId(sessionId)
  
  // 关闭抽屉
  showDrawer.value = false
  
  // 导航到新的会话
  router.push(`/chat/${sessionId}`)
}

const exportChat = () => {
  if (chatExportRef.value) {
    chatExportRef.value.exportChat()
  }
}

const onExportStart = () => {
  message.info('开始导出聊天记录...')
}

const onExportSuccess = () => {
  message.success('聊天记录导出成功！')
}

const onExportError = (error: any) => {
  message.error(`导出失败：${error.message}`)
}

// 加载数据
const loadPromptTemplates = async () => {
  try {
    const { promptService } = await import('../../shared/services')
    const response = await promptService.getPromptTemplates()
    
    if (response.code === 0 && response.data) {
      const templates = response.data.map((template: any) => ({
        id: template.id,
        name: template.name,
        content: template.content,
        description: template.description || '',
        category: template.category || '',
        tags: template.tags || ''
      }))
      chatStore.setPromptTemplates(templates)
    }
  } catch (error) {
    console.error('加载提示词模板失败:', error);
    message.error('加载提示词模板失败')
  }
}

const loadKnowledgeBases = async () => {
  try {
    // 加载知识库的逻辑
    knowledgeBases.value = []
  } catch (error) {
    console.error('加载知识库失败:', error);
  }
}

// 创建新会话
const createNewSession = () => {
  // 生成新的会话ID：用户id_6位随机数
  const userIdValue = numericUserId.value
  const randomNum = Math.floor(Math.random() * 1000000).toString().padStart(6, '0')
  const sessionId = `${userIdValue}_${randomNum}`
  
  // 设置会话标题为"新会话"
  const sessionTitle = "新会话"
  
  // 创建新会话对象
  const newSession = {
    id: sessionId,
    title: sessionTitle,
    createdAt: Date.now(),
    lastActiveAt: Date.now(),
    messageCount: 0,
    userId: userIdValue
  }
  
  // 添加到chatStore的会话列表
  chatStore.addSession(newSession)
  
  // 设置当前会话ID
  userStore.setCurrentSessionId(sessionId)
  chatStore.setCurrentSessionId(sessionId)
  
  // 清空当前会话的消息，确保显示欢迎语句
  chatStore.clearMessages(sessionId)
  
  // 导航到新的会话
  router.push(`/chat/${sessionId}`)
}

// 生命周期
onMounted(() => {
  // 初始化数据
  loadPromptTemplates()
  loadKnowledgeBases()
})
</script>

<style scoped>
.footer-tools {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 8px;
  background: transparent;
  border: none;
}

.tools-left, .tools-right {
  display: flex;
  align-items: center;
  gap: 8px;
}

.footer-tool-icon {
  font-size: 18px;
  color: #6c757d;
  cursor: pointer;
  transition: all 0.2s ease;
  padding: 4px;
  border-radius: 4px;
  opacity: 0.8;
}

.footer-tool-icon:hover {
  color: #007AFF;
  background: rgba(0, 122, 255, 0.05);
  opacity: 1;
}

.footer-tool-icon.memory-enabled,
.footer-tool-icon.tools-enabled {
  color: #007AFF;
  opacity: 1;
}

.footer-tool-icon.prompt-enabled,
.footer-tool-icon.knowledge-enabled {
  color: #28a745;
  opacity: 1;
}

.footer-tool-icon.prompt-active,
.footer-tool-icon.knowledge-active {
  background: rgba(40, 167, 69, 0.05);
  opacity: 1;
}

.popover-text {
  font-size: 12px;
  color: #6c757d;
}

.prompt-template-selector,
.knowledge-base-selector {
  width: 280px;
  max-height: 400px;
}

.prompt-header,
.knowledge-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e9ecef;
}

.prompt-title,
.knowledge-title {
  font-weight: 600;
  color: #495057;
}

.template-list,
.knowledge-list {
  max-height: 300px;
}

.template-item,
.knowledge-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  margin-bottom: 4px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.template-item:hover,
.knowledge-item:hover {
  background: #f8f9fa;
}

.template-item.selected,
.knowledge-item.selected {
  background: #e3f2fd;
  color: #1976d2;
}

.template-item-name,
.knowledge-item-name {
  font-size: 14px;
  flex: 1;
}

.knowledge-item-check {
  color: #16baaa;
}
</style>